from flask import Flask, request, send_file
import subprocess
import os
import time

app = Flask(__name__)


@app.route('/')
def index():
    return 'Hello, World!'


@app.route('/index')
def index2():
    return 'index!'


# 停止 Flask 应用程序


@app.route('/shutdown', methods=['POST', 'GET'])
def shutdown():
    shutdown_func = request.environ.get('werkzeug.server.shutdown')
    if shutdown_func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    shutdown_func()
    return 'Shutting down...'


# 接受tex文件，保存到/home/latex目录下，并渲染成pdf文件，并返回给django端
@app.route('/tex2pdf', methods=['POST', 'GET'])
def tex2pdf():
    try:
        # 接收 a.tex 文件流并保存
        tex_file_path = os.path.join("/home/latex", "a.tex")
        with open(tex_file_path, 'wb') as tex_file:
            tex_file.write(request.data)

        # command = f"xelatex {tex_file_path}"
        command = f'/home/latex/tex2pdf.sh {tex_file_path}'
        subprocess.run(command, shell=True, check=True)
        time.sleep(2)
        # return 'ok'
        count = 0
        # 分离文件名和扩展名
        # name, ext = os.path.splitext(tex_file_path)
        # 获取文件所在的目录
        directory = '/home/flask-app'
        # pdf_file_path = directory + name + '.pdf'
        pdf_file_path = directory + '/a.pdf'
        flag = False
        while count < 50:
            if os.path.exists(pdf_file_path):
                flag = True
                break
            count += 1
            time.sleep(0.1)
        if flag:
            print('pdf文件渲染完成')
            # 发送 a.pdf 文件流（假设a.pdf事先存在）
            pdf_file_path = os.path.join("/home/flask-app", "a.pdf")
            if not os.path.exists(pdf_file_path):
                print('pdf文件渲染失败！')
                return "error", 401
            return send_file(pdf_file_path, as_attachment=True, attachment_filename='a.pdf', mimetype='application/pdf')
        else:
            print('pdf文件渲染失败！')
            return "error", 401
    except:
        return "error", 400


if __name__ == '__main__':
    # app.run()
    app.run(host='0.0.0.0', port=5000)
